<template>
  <div>
    <div>
      <el-button type="primary" @click="onSubumit">确定</el-button>
    </div>
    <div>JSON编辑器</div>
    <CodeEdit
      v-model="jsonStr"
      language="json"
    ></CodeEdit>
    <div>代码</div>
    <CodeHighlightjs
      language="JavaScript"
      :code="code"
    ></CodeHighlightjs>
    <div>生成的UI效果</div>
    <DynamicForm
      ref="DynamicFormRef"
      v-model="formData"
      :form-config="formConfig"
    ></DynamicForm>
  </div>
</template>

<script>
import CodeHighlightjs from "@localModules/ZhiXinLib/components/CodeHighlightjs";
import {FormConfig} from "@localModules/ZhiXinLib/element-components/dynamic-form/ConfigType";
import typeOfUtils from "@localModules/ZhiXinLib/utils/type-of-utils";
import beautify from 'js-beautify/js'
import DynamicForm from '@localModules/ZhiXinLib/element-components/dynamic-form'
import CodeEdit from "@localModules/ZhiXinLib/components/CodeEdit";
export default {
  name: "FormData2FormConfig",
  components:{
    CodeEdit,
    CodeHighlightjs,
    DynamicForm,
  },
  data(){
    return{
      jsonStr:`{
        "string":"string",
        "number":1
      }`,
      code:`[]`,
      formData:{}
    }
  },
  computed:{
    formConfig(){
      return new FormConfig({},eval(this.code))
    }
  },
  methods:{
    // 检测json格式
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          const obj = JSON.parse(str);
          if(typeof obj == 'object' && obj ){
            return true;
          }else{
            return false;
          }
        } catch(e) {
          return false;
        }
      }else if (typeof str == 'object'  && str) {
        return true;
      }
    },
    onSubumit(){
      if (!this.isJSON(this.jsonStr)){
        this.$message.error(`json格式错误`)
        return false
      }
      const data=JSON.parse(this.jsonStr)
      this.code = '['
      Object.keys(data).forEach(key=>{
        this.code+=this.getFormItem(key,data[key])
      })
      this.code+=']'
      this.code = beautify(this.code, {indent_size: 2})
      this.$nextTick(()=>{
        this.$refs.DynamicFormRef.initValue()
      })
    },
    getFormItem(key,value){
      if(typeOfUtils.isString(value)){
        return `{
           span: 12,
              type: 'input',
              label: '${key}',
              prop: '${key}',
              props: {
                clearable: true,
              },
               initValue: '${value}',
        },`
      } else if(typeOfUtils.isNumber(value)){
        return `{
           span: 12,
              type: 'inputNumber',
              label: '${key}',
              prop: '${key}',
              props: {
                clearable: true,
              },
               initValue: '${value}',
        },`
      }
    }
  }
}
</script>

<style scoped lang="scss">

</style>
